<?php
namespace Modules\Backstage\Controllers;

class UserController extends \Phalcon\Mvc\Controller {
	public function beforeExecuteRoute(\Phalcon\Mvc\Dispatcher $dispatcher) {
		$this -> response -> setStatusCode(200, 'OK') -> sendHeaders() -> setContentType('application/json', 'UTF-8');

		$service = $this -> account::getServiceInstance() -> checkLogin($this -> request -> getQuery('token', 'string', null));
		if($service['code'] != 0) {
			$this -> response -> setJsonContent(['code'=>-1,'msg'=>$service['message'] ]) -> send();
			exit;
		}

		$this -> account::getAclInstance() -> check($this, $dispatcher, $service['model'] -> roles_id);
	}


	public function indexAction() {
		$query = $this -> request -> getQuery();
		if(!isset($query['page'])) {
			$query['page'] = 1;
		} else if($query['page'] <= 0)  {
			$query['page'] = 1;
		} else {
			$query['page'] = abs($query['page']);
		}

		if(!isset($query['limit'])) {
			$query['limit'] = 10;
		} else if($query['limit'] <= 0)  {
			$query['limit'] = 10;
		} else {
			$query['limit'] = abs($query['limit']);
		}

		$parameters = [];
		if(isset($query['account']) && !empty($query['account'])) {
			$parameters['conditions'] = 'u.account = "' . $query['account'] . '"';
		}
		
		$service = $this -> user::getLogicInstance() -> pager($parameters, $query['limit'], $query['page']);
		if($service['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$service['code'],'msg'=>$service['message']]);
		}

		$pager = [
			'items' => [],
			'first' => $service['pager'] -> first,
			'before' => $service['pager'] -> before,
			'current' => $service['pager'] -> current,
			'last' => $service['pager'] -> last,
			'next' => $service['pager'] -> next,
			'total_pages' => $service['pager'] -> total_pages,
			'total_items' => $service['pager'] -> total_items,
			'limit' => $service['pager'] -> limit
		];

		$jwt = new \Components\Account\User\JWT();
		foreach($service['pager'] -> items as $k => $item) {
			$pager['items'][$k] = $item;
			$pager['items'][$k]['token'] = $jwt -> setToken(['account'=>['user_id'=>$item['user_id']]]);
		}
		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'Success', 'pager' => $pager]);
	}
}